package com.mb.ship.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mb.ship.service.IShipService;
import com.mb.ship.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 快递接口服务实现
 *
 * @author liliping
 * @create 2019-04-16 12:11 PM
 **/
@Service("shipService")
@ConfigurationProperties()
@Slf4j
public class ShipServiceImpl implements IShipService {


    @Value("${ship.appCode}")
    private String appCode;

    @Override
    public JSONObject shipQuery(JSONObject req) {
        JSONObject resp = null;
        String no = req.getString("no");
        String type = req.getString("type");

        String host = "https://wuliu.market.alicloudapi.com";
        String path = "/kdi";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //格式为:Authorization:APPCODE 83359fd73fe11248385f570e3c139xxx
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("no", no);
        querys.put("type", type);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
            String ret = EntityUtils.toString(response.getEntity());
            log.info("shipQuery ret:" +ret );
            if(StringUtils.isNotBlank(ret)){
                resp = JSONObject.parseObject(ret);
            }
        } catch (Exception e) {
            log.error("shipQuery Exception ",e);
        }
        return resp;
    }
}
